import React, { useEffect, useState } from 'react';
import { Card, Descriptions, Button, Spin, message } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { resourceDetail, resourceListTree } from '@/services/system/resource';
import { useModel } from '@umijs/max';
import CustomPageContainer from '@/components/CustomPageContainer';
import { useCommonStyles } from '@/styles/commonStyles';

// 资源类型映射
const resourceTypeMap: Record<string, string> = {
  menu: '菜单',
  page: '页面',
  button: '按钮',
  api: '接口'
};

// 操作类型映射
const actionTypeMap: Record<string, string> = {
  add: '新增',
  edit: '编辑',
  delete: '删除',
  view: '查看'
};

interface TreeDataItem {
  id: string;
  resourceId: string;
  resourceName: string;
  children?: TreeDataItem[];
  [key: string]: any;
}

const ResourceManageView: React.FC = () => {
  const { styles } = useCommonStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [resourceData, setResourceData] = useState<any>({});
  const [parentResourceName, setParentResourceName] = useState<string>('顶级资源');
  const record = location.state?.record || {};
  const { institutionId, institutionRoleId, departmentId, positionId } = useModel('auth');

  // 获取资源树数据
  useEffect(() => {
    const fetchResourceTree = async () => {
      try {
        const params = {
          institutionId,
          institutionRoleId,
          departmentId,
          positionId,
        };
        const response = await resourceListTree(params);
        if (response.code === 200) {
          console.log('资源树数据:', response.data);
          // 递归查找父级资源名称
          const findParentResource = (data: TreeDataItem[]): string => {
            for (const item of data) {
              console.log('当前项:', item);
              console.log('对比:', item.resourceId, resourceData.resourceParentId);
              if (item.resourceId === resourceData.resourceParentId) {
                console.log('找到匹配项:', item.resourceName);
                return item.resourceName;
              }
              if (item.children && item.children.length > 0) {
                const found = findParentResource(item.children);
                if (found) {
                  return found;
                }
              }
            }
            return '';
          };

          // 如果有父级资源ID，查找对应的名称
          if (resourceData.resourceParentId && resourceData.resourceParentId !== '0') {
            console.log('开始查找父级资源，parentId:', resourceData.resourceParentId);
            const parentName = findParentResource(response.data);
            console.log('找到的父级资源名称:', parentName);
            setParentResourceName(parentName || '顶级资源');
          } else {
            setParentResourceName('顶级资源');
          }
        } else {
          message.error(response.msg || '获取资源树失败');
        }
      } catch (error) {
        console.error('获取资源树失败:', error);
        message.error('获取资源树失败');
      }
    };

    fetchResourceTree();
  }, [resourceData.resourceParentId, institutionId, institutionRoleId, departmentId, positionId]);

  // 获取详情数据
  useEffect(() => {
    const fetchData = async () => {
      if (!record.resourceId) return;

      try {
        setLoading(true);
        const response = await resourceDetail({
          resourceId: record.resourceId,
          institutionId,
          institutionRoleId,
          departmentId,
          positionId,
        });

        if (response.code === 200) {
          const detailData = {
            ...response.data,
            iconPath: response.data.iconPath || response.data.icon,
            resourceParentId: response.data.resourceParentId || '0'
          };
          console.log('详情数据:', detailData);
          setResourceData(detailData);
        } else {
          message.error(response.msg || '获取详情失败');
        }
      } catch (error) {
        console.error('获取详情失败:', error);
        message.error('获取详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [record.resourceId, institutionId, institutionRoleId, departmentId, positionId]);

  const handleBack = () => {
    navigate('/system/resourcemanage');
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.formContainer}>
            <div className={styles.title}>资源详情</div>
            <Spin spinning={loading}>
              <Descriptions column={2} bordered>
                <Descriptions.Item label="资源名称" span={1}>
                  {resourceData.resourceName}
                </Descriptions.Item>
                <Descriptions.Item label="资源别名" span={1}>
                  {resourceData.alias}
                </Descriptions.Item>
                <Descriptions.Item label="上级资源" span={1}>
                  {parentResourceName}
                </Descriptions.Item>
                <Descriptions.Item label="路由地址" span={1}>
                  {resourceData.path}
                </Descriptions.Item>
                <Descriptions.Item label="资源类型" span={1}>
                  {resourceTypeMap[resourceData.resourceType as string] || resourceData.resourceType || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="操作按钮类型" span={1}>
                  {actionTypeMap[resourceData.action as string] || resourceData.action || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="资源图标" span={1}>
                  {resourceData.iconPath || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="排序" span={1}>
                  {resourceData.sort}
                </Descriptions.Item>
                <Descriptions.Item label="是否打开新页面" span={1}>
                  {resourceData.isOpen === 1 ? '是' : '否'}
                </Descriptions.Item>
                <Descriptions.Item label="是否显示" span={1}>
                  {resourceData.visible === 1 ? '显示' : '隐藏'}
                </Descriptions.Item>
                <Descriptions.Item label="资源备注" span={2}>
                  {resourceData.remark || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间" span={1}>
                  {resourceData.createTime || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间" span={1}>
                  {resourceData.updateTime || '-'}
                </Descriptions.Item>
              </Descriptions>

              <div className={styles.buttonGroup}>
                <Button onClick={handleBack}>
                  返回
                </Button>
              </div>
            </Spin>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default ResourceManageView;
